<template>
  <d2-container>
    <el-main>

      <!-- <h3>选择校区</h3>
      <el-select v-model="school" filterable placeholder="可输入名称搜索" @change="schoolSelected" :disabled="disabled">
        <el-option
                v-for="item in schoolList"
                :key="item._id"
                :label="item.name"
                :value="item._id"
        ></el-option>
      </el-select> -->

      <h3>选择部门</h3>
      <el-checkbox-group v-model="department" :disabled="disabled">
        <el-checkbox-button v-for="value in departmentList" :label="value._id" :key="value._id">{{value.name}}</el-checkbox-button>
      </el-checkbox-group>



      <h3>考勤组名称：</h3>
      <el-input placeholder="请输入考勤组名称" v-model="name" :disabled="disabled"></el-input>


      <h3>考勤开始时间范围</h3>

      <div style="margin:20px 0;">
        <el-radio-group v-model="weekRadio">
          <el-radio-button label="0">周日</el-radio-button>
          <el-radio-button label="1">周一</el-radio-button>
          <el-radio-button label="2">周二</el-radio-button>
          <el-radio-button label="3">周三</el-radio-button>
          <el-radio-button label="4">周四</el-radio-button>
          <el-radio-button label="5">周五</el-radio-button>
          <el-radio-button label="6">周六</el-radio-button>
        </el-radio-group>
      </div>
        <el-row v-for="(timeList,index) in  workHours[weekRadio].hours" :key="index">
          <el-time-picker  style="display: block;margin-bottom: 10px;height:50px;display: inline-block;"
                is-range
                v-model="workHours[weekRadio].hours[index]"
                range-separator="至"
                start-placeholder="开始时间"
                end-placeholder="结束时间"
                placeholder="选择时间范围"
                @change="changeTime"
                arrow-control
                :disabled="disabled">

          </el-time-picker>
          <el-button type="danger" round icon="el-icon-delete" size="small" @click="removeInterval(index)" style='margin-left: 10px' :disabled='disabled'></el-button>
        </el-row>


      <el-button type="primary" @click="addTimeRange" :disabled="disabled">增加考勤区间</el-button>


     
      </div>

<!--       <h3>考勤时间</h3>
      <el-checkbox-group v-model="recurrence" :disabled="disabled">
        <el-checkbox-button v-for="day in recurrenceOption" :label="day.value" :key="day.label">{{day.label}}</el-checkbox-button>
      </el-checkbox-group> -->
     <!--  <h3>最大打卡距离（米）</h3>
         <el-input
              placeholder=""
              min="0"
              v-model="range"
              :disabled="disabled"
      ></el-input> -->

      <h3>考勤组备注</h3>
      <el-input
              placeholder=""
              min="0"
              v-model="remark"
              :disabled="disabled"
      ></el-input>

      <h3>考勤组启用状态</h3>
      <el-radio v-model="status" :label="1">启用</el-radio>
      <el-radio v-model="status" :label="2">停用</el-radio>

<!-- 
      <div id="container123" style="margin-top:20px;width:300px;height:300px;"></div>

      <h3>搜索地址</h3>
        <el-input placeholder="请输入地址" v-model="address" :disabled="disabled" style="width:600px">
          <el-button slot="append" icon="el-icon-search" @click="searchAddress"></el-button>
        </el-input>

      <h3>经度</h3>
      <el-input
              placeholder=""
              min="0"
              v-model="longitude"
              :disabled="disabled"
      ></el-input>

      <h3>纬度</h3>
      <el-input
              placeholder=""
              min="0"
              v-model="latitude"
              :disabled="disabled"
      ></el-input> -->
    </el-main>

    <el-footer>
      <el-button type="primary" @click="submit" :disabled="disabled">提交</el-button>
      <el-button @click="edit" v-show="editShow">修改</el-button>
    </el-footer>

  </d2-container>
</template>

<script>
// import { request } from "http";
import request from "@/plugin/axios";
import { constants } from "crypto";
import {mapState} from "vuex";

export default {
  data() {
    return {
      id:undefined,
      editShow: false,
      disabled: false,
      name: undefined,
      recurrence: [],
      recurrenceOption: [
        {label: '星期一', value: 1},
        {label: '星期二', value: 2},
        {label: '星期三', value: 3},
        {label: '星期四', value: 4},
        {label: '星期五', value: 5},
        {label: '星期六', value: 6},
        {label: '星期天', value: 0}],
      remark:undefined,
      status:1,
      school:undefined,
      schoolList:[],
      department:[],
      departmentList:[],
      disabled:false,
      startTime:[],
      endTime:[],
      range:undefined,
      timeRange:[],
      range : 50,
      weekRadio: 0,
      workHours: [
        { day: 0, hours: [] },
        { day: 1, hours: [] },
        { day: 2, hours: [] },
        { day: 3, hours: [] },
        { day: 4, hours: [] },
        { day: 5, hours: [] },
        { day: 6, hours: [] }
      ],
      //地图
      address:undefined,
      longitude:0,//经度
      latitude:0,//纬度
      city:''

    };
  },
  computed: {
    ...mapState('d2admin/user', ['info']),
  },
  methods: {

    changeTime(){
    },
    addTimeRange(){
      // this.timeRange.push([new Date(2019, 9, 1, 8,0), new Date(2019,9,1,18,0)])
      // this.timeRange.push({})
      this.workHours[this.weekRadio].hours.push([new Date(2019, 9, 1, 8,0), new Date(2019,9,1,18,0)])
    },

    submit() {
      for(let i=0;i<this.timeRange.length;i++){
        if(this.timeRange[i-1] !=undefined){
          if(this.timeRange[i-1][1]>this.timeRange[i][0]){
            this.$alert('请修改考勤时间段', '考勤时间冲突', {
              confirmButtonText: '确定',
              callback: action => {
              }
            });
              return false
          }
        }
      }
      let data = {};
      data.name = this.name
      data.recurrence = this.recurrence
      // data.longitude = this.longitude
      // data.latitude = this.latitude
      let url = "/workRecordGroup/addWorkRecordGroup";
      if (this.id != undefined) {
        data.id = this.id;
        url = "/workRecordGroup/updateWorkRecordGroup";
      }
      data.remark = this.remark
      data.status = this.status
      data.department = this.department
      data.school = this.school
      // data.range = this.range 

        // var jojo = []
        // for (var i = 0 ; i <this.timeRange.length;i++){
        //   let c1 = this.timeRange[i][0]
        //   let c2 = this.timeRange[i][1]

        //   c1 = new Date(2019,9,1,c1.getHours(),c1.getMinutes(),c1.getSeconds())
        //   c2 = new Date(2019,9,1,c2.getHours(),c2.getMinutes(),c2.getSeconds())
        //   jojo.push([c1,c2])
        // }
        // var jojo = jojo.sort(function(a,b){return b[0]-a[0]})
        // var i = 1;
        // var message = 0
        // var temp = 1
        // while (i < jojo.length ){
        //   var j = 0
        //   while (j < i){
        //     if (jojo[j][0] < jojo[i][1]){
        //       temp = j
        //       message = 1
        //       i = jojo.length
        //       j = i

        //     }
        //     else{
        //       j = j +1
        //     }
        //   }
        //   i += 1
        // }
        // if (message != 0){
        //   this.$alert("时间段不能重合", "时间重合,请修改", {
        //     confirmButtonText: "确定"
        //   });
        //   // jojo.splice(temp,1)
        //   // this.classTime[e].hours = jojo
        //   return false
        // }


      // this.timeRange.forEach(((value, index) => {
      //   console.log(value,'wtf value',value[0].getHours(),value[0].getMinutes(),value[0].getSeconds())
      //   let v1 = (value[0].getHours() < 10 ? ('0' + value[0].getHours()) : value[0].getHours()) + ':' + (value[0].getMinutes() < 10 ? ('0' + value[0].getMinutes()) : value[0].getMinutes()) + ':' + (value[0].getSeconds() < 10 ? ('0' + value[0].getSeconds()) : value[0].getSeconds())
      //   let v2 = (value[1].getHours() < 10 ? ('0' + value[1].getHours()) : value[1].getHours()) + ':' + (value[1].getMinutes() < 10 ? ('0' + value[1].getMinutes()) : value[1].getMinutes()) + ':' + (value[1].getSeconds() < 10 ? ('0' + value[1].getSeconds()) : value[1].getSeconds())
      //   //   console.log(v1,v2,'vvv')
      //   this.startTime.push(v1)
      //   this.endTime.push(v2)
      // }))

      let jojo = []
      let message = 0
      for (var i = 0 ; i < this.workHours.length ; i++){
        this.workHours[i].hours = this.workHours[i].hours.sort(function(a,b){return a[0] - b[0]})
        for (var j = 0 ; j < this.workHours[i].hours.length - 1;j++){
          if (this.workHours[i].hours[j + 1][0] < this.workHours[i].hours[j][1]){
            message = 1
          }
        }
      }
      if (message != 0){
          this.$alert("时间段不能重合", "时间重合,请修改", {
            confirmButtonText: "确定"
          });
          return false
      }
      for (var i = 0 ; i < this.workHours.length ; i++){
        for (var j = 0 ; j < this.workHours[i].hours.length ;j++){
          let value = this.workHours[i].hours[j]
          this.workHours[i].hours[j][0] = (value[0].getHours() < 10 ? ('0' + value[0].getHours()) : value[0].getHours()) + ':' + (value[0].getMinutes() < 10 ? ('0' + value[0].getMinutes()) : value[0].getMinutes()) + ':' + (value[0].getSeconds() < 10 ? ('0' + value[0].getSeconds()) : value[0].getSeconds())
           this.workHours[i].hours[j][1] = (value[1].getHours() < 10 ? ('0' + value[1].getHours()) : value[1].getHours()) + ':' + (value[1].getMinutes() < 10 ? ('0' + value[1].getMinutes()) : value[1].getMinutes()) + ':' + (value[1].getSeconds() < 10 ? ('0' + value[1].getSeconds()) : value[1].getSeconds())
        }
      }
     data.hours = this.workHours

      // console.log(this.startTime,this.endTime,'jboboo')
      // return false
      // data.startTime = this.startTime;
      // data.endTime = this.endTime;
      request({
        url: url,
        method: "post",
        data
      }).then(res => {
        if (res.code == 200) {
          this.refresh = true
          this.name = undefined
          this.recurrence = undefined
          // this.longitude = undefined
          // this.latitude = undefined
          this.remark = undefined
          this.status  = undefined
          this.department = undefined
          this.school = undefined
          this.startTime = undefined
          this.endTime = undefined
          this.timeRange = undefined
          this.workHours = undefined
          // this.range = 50

          this.$router.push({path:"/work-group-list"})

          this.$alert("", "提交成功", {
            confirmButtonText: "确定"
          });

        }
        // 返回数据
      });
    },
    edit() {
      this.disabled = false;
    },
    schoolSelected() {
      this.getDepartmentList(1, 9999, this.school);
    },

    removeInterval(index){
      this.workHours[this.weekRadio].hours.splice(index,1)
    },
    getSchoolList(page, pageSize) {
      // let data = {};
      // (data.page = page), (data.pageSize = pageSize);
      // request({
      //   url: "/school/getSchoolList",
      //   method: "post",
      //   data
      // }).then(res => {
      //   this.schoolList = res.data.school;
      //   // 返回数据
      // });

      this.schoolList = this.info.school;
    },

    getDepartmentList(page, pageSize, school) {
      let data = {};
      (data.page = page), (data.pageSize = pageSize), (data.school = school);
      request({
        url: "/department/getDepartmentList",
        method: "post",
        data
      }).then(res => {
        this.departmentList = res.data.department;
      });
    },
    addzero(a){
      if (a < 10){
        return '0' + a
      }
      else{
        return String(a)
      }
    },
    getWorkGroupOne(id){
      request({
        url: "/workRecordGroup/getWorkGroupOne",
        method: "post",
        data:{id:id}
      }).then(res => {
        this.id = res.data._id
        // this.school = res.data.school
        this.getDepartmentList(1, 9999,this.school)
        this.department = res.data.department;
        this.name = res.data.name
        this.remark = res.data.remark
        this.status = res.data.status
        this.longitude = res.data.longitude[0]
        this.latitude = res.data.latitude[0]
        this.recurrence = res.data.recurrence
        this.range = res.data.range || 50
        let tempTimeRange = []
        for(let i=0;i<res.data.startTime.length;i++){
          tempTimeRange.push([])
          tempTimeRange[i][0] = new Date("2019-09-01 " + res.data.startTime[i])
          tempTimeRange[i][1] = new Date("2019-09-01 " + res.data.endTime[i])
        }
        this.timeRange = tempTimeRange

        for (let i = 0 ; i < res.data.hours.length ; i++){
          for (let j = 0 ;j < res.data.hours[i].hours.length ;j++){
            this.workHours[i].hours.push([new Date('2019-09-01 ' + res.data.hours[i].hours[j][0]),new Date('2019-09-01 ' + res.data.hours[i].hours[j][1])])
          }
        }
        // this.setMap(res.data.latitude[0],res.data.longitude[0])
      });
    },

    searchAddress(){
      let that = this
      let geocoder = new qq.maps.Geocoder({
        complete: function(result) {
          console.log(result)
          let position = {}
          that.longitude = result.detail.location.lng,//经度
          that.latitude = result.detail.location.lat,//纬度
          position.lat = result.detail.location.lat
          position.lng = result.detail.location.lng
          position.city = result.detail.addressComponents.city
          that.showPosition(position)
        },
        //若服务请求失败，则运行以下函数
        error: function(result) {
            alert("出错了，请输入详细的地址（包含省市）！！！");
        }
      });
      geocoder.getLocation(this.address);
    },




    //定位获得当前位置信息
    getMyLocation() {
      let geolocation = new qq.maps.Geolocation("ANPBZ-OZFWO-6NIWX-SILNK-4RQT5-3SFFW", "弈飞围棋");
      geolocation.getIpLocation(this.showPosition, this.showErr);
    },

    showPosition(position) {
      console.log(position);
      this.latitude = position.lat;
      this.longitude = position.lng;
      this.city = position.city;
      // this.setMap(position.lat,position.lng);
    },

    showErr() {
      this.getMyLocation();//定位失败再请求定位，测试使用
    },

//第二部分
    //位置信息在地图上展示
    setMap(latitude,longitude) {
      //步骤：定义map变量 调用 qq.maps.Map() 构造函数   获取地图显示容器
      //设置地图中心点


      let myLatlng = new qq.maps.LatLng(latitude,longitude);

      //定义工厂模式函数
      let myOptions = {
        zoom: 13,               //设置地图缩放级别
        center: myLatlng,    //设置中心点样式
        mapTypeId: qq.maps.MapTypeId.ROADMAP  //设置地图样式详情参见MapType
      }
      // //获取dom元素添加地图信息
      let  map = new qq.maps.Map(document.getElementById("container123"), myOptions);


      let marker = new qq.maps.Marker({
        position: new qq.maps.LatLng(latitude,longitude),
        map: map
      });
      var _this = this

      qq.maps.event.addListener(map,'click',function (event) {

        marker.setMap(null);
        _this.longitude = event.latLng.getLng();
        _this.latitude = event.latLng.getLat();
        marker=new qq.maps.Marker({
          position:new qq.maps.LatLng(event.latLng.getLat(),event.latLng.getLng()),
          map:map
        });
      })


//第三部分
//       //给定位的位置添加图片标注
//       var marker = new qq.maps.Marker({
//         position: myLatlng,
//         map: map
//       });
//
//       //给定位的位置添加文本标注
//       var marker = new qq.maps.Label({
//         position: myLatlng,
//         map: map,
//         content:'这是我当前的位置，偏差有点大，哈哈'
//       });
    },


  },
  beforeRouteLeave(to,from,next){
        if (this.refresh){
          to.meta.refresh = 'a'
          this.refresh = undefined
        }
        if (this.$route.query.id == undefined){
            from.meta.keep = true
          from.meta.name = this.name
          from.meta.recurrence = this.recurrence
          from.meta.remark = this.remark
          from.meta.status  = this.status
          from.meta.department = this.department
          from.meta.school = this.school
          from.meta.startTime = this.startTime
          from.meta.endTime = this.endTime
          from.meta.timeRange = this.timeRange
        }

        next()
        },
        beforeRouteEnter(to,from,next){
            if (to.meta.keep){
                to.meta.keep = undefined
                next(v=>{
                  v.name = to.meta.name
                  v.recurrence = to.meta.recurrence
                  v.remark = to.meta.remark
                  v.status  = to.meta.status
                  v.department = to.meta.department
                  v.school = to.meta.school
                  v.startTime = to.meta.startTime
                  v.endTime = to.meta.endTime
                  v.timeRange = to.meta.timeRange
                  to.meta.name = undefined
                  to.meta.recurrence = undefined
                  to.meta.remark = undefined
                  to.meta.status  = undefined
                  to.meta.department = undefined
                  to.meta.school = undefined
                  to.meta.startTime = undefined
                  to.meta.endTime = undefined
                  to.meta.timeRange = undefined
                              
                })
            }
            else{
                next()
            }

        },

  created() {
    this.getSchoolList(1, 99999);
    this.getMyLocation()
    this.school = this.info.school[0]._id
    if (this.$route.query.id != undefined) {
      this.editShow = true;
      this.disabled = true;
      this.getWorkGroupOne(this.$route.query.id)
    }
    this.getDepartmentList(1, 9999, this.school);
  }
};
</script>
